<?php


namespace app\admin\service;


class MenuService
{
    /**
     * 根据parent_id分类
     * @param array $arr 数据(多维数组)
     * @param int $id
     * @return array
     */
    public function categoryMenuByParentId(array $arr, int $id = -1): array {
        return $this->getTreeCategory($arr, $id);
    }

    // 递归获取无限极分类
    private function getTreeCategory(array $arr, $parent_id): array {
        $tree = array();
        foreach ($arr as $k => $v) {
            if ($v["parent_id"] == $parent_id) {
                unset($arr[$k]);
                if (!empty($arr)) {
                    $children = $this->getTreeCategory($arr, $v["id"]);
                    if (!empty($children)) {
                        $v["children"] = $children;
                    }
                }
                $tree[] = $v;
            }
        }
        return $tree;
    }

    /**
     * 更新状态
     * @param array $arr
     * @param int $status
     * @return array
     */
    public function updateStatusList(array $arr, int $status) {
        $updateList = [];
        foreach ($arr as $item) {
            if(is_array($item['children']??false)){
                $dataArr = $this->updateStatusList($item['children'], $status);
                foreach ($dataArr as $updateItem) {
                    array_push($updateList, $updateItem);
                }
            }
            array_push($updateList, ['id'=>$item['id'], 'status'=>$status]);
        }
        return $updateList;
    }

}